package org.csu.mypetstore.controller;

import org.apache.catalina.Manager;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;
import org.csu.mypetstore.service.SignInService;
import org.csu.mypetstore.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/manage")
public class ManagerController {
    @Autowired
    private OrderService orderService;

    @Autowired
    CatalogService catalogService;

    @Autowired
    private List<Order> orderList;
    @Autowired
    private Order order;
    @Autowired
    private Order order1;

    @Autowired
    HttpSession session;

    @Autowired
    SignInService accountService;

    @Autowired
    SignInService signInService;

    @Autowired
    Account account;

    @GetMapping("/viewCategory")
    public String viewCategory()
    {
        List<Category> categoryList = catalogService.getCategoryList();
        session.setAttribute("categoryList",categoryList);
        return "manage/catalog/ManageCategory";
    }
    @GetMapping("/deleteCategory")
    @ResponseBody
    public List<Category> deleteCategory(String categoryId){
        List<Product> productList = catalogService.getProductListByCategory(categoryId);
        for (int i=0;i<productList.size();i++){
            catalogService.deleteItemByProductId(productList.get(i).getProductId());
        }
        catalogService.deleteProductByCategoryId(categoryId);
        catalogService.deleteCategoryById(categoryId);
        List<Category> categoryList = catalogService.getCategoryList();
        return categoryList;
    }

    @GetMapping("/viewEditCategory")
    public String viewEditCategory(String categoryId,Model model){
        Category category = catalogService.getCategory(categoryId);
        model.addAttribute("category",category);
        return "manage/catalog/categoryEdit";

    }
    @GetMapping("/editCategory")
    public List<Category> editCategory(String categoryId,String name,String description){
        Category category = catalogService.getCategory(categoryId);
        category.setName(name);
        category.setDescription(description);
        catalogService.editCategory(category);
        List<Category> categoryList = catalogService.getCategoryList();
        return categoryList;
    }
    @GetMapping("/viewProduct")
    public String viewProduct(String categoryId, Model model)
    {
            Category category = catalogService.getCategory(categoryId);
            List<Product> productList = catalogService.getProductListByCategory(categoryId);
            session.setAttribute("category",category);
            model.addAttribute("productList",productList);
            return "manage/catalog/ManageProduct";
    }

    @GetMapping("/deleteProduct")
    @ResponseBody
    public List<Product> deleteProduct(String categoryId,String productId){
        catalogService.deleteItemByProductId(productId);
        catalogService.deleteProduct(productId);
        List<Product> productList = catalogService.getProductListByCategory(categoryId);
        return productList;
    }

    @GetMapping("/vieweditProduct")
    public String viewEditProduct(String productId,Model model){
        Product product = catalogService.getProduct(productId);
        model.addAttribute("product",product);
        return "manage/catalog/productEdit";
    }
    @GetMapping("/viewItem")
    public String viewItem(String productId,Model model)
    {
        Product product = catalogService.getProduct(productId);
        List<Item> itemList = catalogService.getItemListByProduct(productId);
        session.setAttribute("product",product);
        model.addAttribute("itemList",itemList);
        session.setAttribute("itemList",itemList);
            return "manage/catalog/ManageItem";
    }
    @GetMapping("/itemEdit")
    public String itemEditGet(String id,Model model)
    {
        Item item = catalogService.getItem(id);
        model.addAttribute("item",item);
        return "manage/catalog/itemEdit";
    }
    @PostMapping("/itemEdit")
    public String itemEditPost(Model model, HttpServletRequest request, Item item, HttpSession httpSession)
    {
            catalogService.updateItem(item);
            catalogService.updateInventory(item);
//            String productId = item.getProductId();
//        Product product = catalogService.getProduct(productId);
//        List<Item> itemList = catalogService.getItemListByProduct(productId);
//        model.addAttribute("product",product);
//        model.addAttribute("itemList",itemList);
        Product product = (Product) session.getAttribute("product");
        List<Item> itemList = catalogService.getItemListByProduct(product.getProductId());
        model.addAttribute("itemList",itemList);
        session.setAttribute("itemList",itemList);
        model.addAttribute("msg", "修改成功");
        return "manage/catalog/itemEdit";
    }

    @GetMapping("/itemDelete")
    public String itemDelete(String id)
    {
        Item item = catalogService.getItem(id);
        ReItem reItem = new ReItem();
        reItem.setItemId(item.getItemId());
        reItem.setProductId(item.getProductId());
        reItem.setListPrice(item.getListPrice());
        reItem.setUnitCost(item.getUnitCost());
        reItem.setSupplierId(item.getSupplierId());
        reItem.setStatus(item.getStatus());
        reItem.setAttribute1(item.getAttribute1());
        reItem.setProduct(item.getProduct());
        reItem.setQuantity(item.getQuantity());
        reItem.setRecovered(new Date());
//        catalogService.insertReItem(reItem);
        catalogService.deleteItem(item);
        return "manage/catalog/ManageItem";
    }

    @GetMapping("/itemAdd")
    public String itemAddGet(String productId,Model model)
    {
        System.out.println(productId);
        session.setAttribute("productId",productId);
        return "manage/catalog/itemAdd";
    }
    @PostMapping("/itemAdd")
    public String itemAddPost(Model model, HttpServletRequest request, Item item, HttpSession httpSession)
    {
        catalogService.addItem(item);
        catalogService.addInventory(item);
        Product product = (Product) session.getAttribute("product");
        List<Item> itemList = catalogService.getItemListByProduct(product.getProductId());
        model.addAttribute("msg","增加成功");
        model.addAttribute("itemList",itemList);
        session.setAttribute("itemList",itemList);
        for (int i=0;i<itemList.size();i++) {
            System.out.println("1111" + itemList.get(i).getItemId());
        }
        return "manage/catalog/itemAdd";
    }

    @GetMapping("/orderControl")
    public String orderControl(){
        orderList = orderService.getOrdersList();
        session.setAttribute("allOrderList",orderList);
        return "manage/order/orderManage";
    }

    @GetMapping("/updateOrder")
    public String updateOrder(int orderId){
        order =orderService.getOrder(orderId);
//        List<Order> orderList = orderService.getOrdersByUsername(account.getUsername());
        session.setAttribute("order",order);
        return "manage/order/orderUpdate";
    }

    @PostMapping("/comfirm")
    public String comfireOrder(Order order,Model model){
//        Date orderDate = new Date();
//        order.setOrderDate(orderDate);
//        order.setCourier("UPS");
//        order.setCardType("Visa");
        order.setLocale("CA");
//        order.setStatus("P");
        orderService.updateOrder(order);
        orderList = orderService.getOrdersList();
        session.setAttribute("allOrderList",orderList);
        session.setAttribute("order",order);
        model.addAttribute("msg","修改成功");
        return "manage/order/orderUpdate";
    }

    @GetMapping("/updateItemQuantityAjax")
    public String updateItemQuantityAjax(String orderId, String quantity, String itemId, Model model){
        int Quantity = Integer.parseInt(quantity);
        int orderId1 = Integer.parseInt(orderId);
        order = orderService.getOrder(orderId1);
        for (int i = 0; i < order.getLineItems().size(); i++) {
            if(order.getLineItems().get(i).getItemId().equals(itemId)){
                order.getLineItems().get(i).setQuantity(Quantity);
            }
        }

        orderService.updateOrder(order);
        orderList = orderService.getOrdersList();
        session.setAttribute("allOrderList",orderList);
        return "manage/order/orderUpdate";
    }

    @GetMapping("/toShowOrder")
    public String toShowOrder(int orderId) {
        order =orderService.getOrder(orderId);
        session.setAttribute("order",order);
        return "manage/order/viewOrder";
    }

    @GetMapping("/removeOrder")
    public String removeOrder(int orderId) {
        orderService.removeOrder(orderId);
        orderList = orderService.getOrdersList();
        session.setAttribute("allOrderList",orderList);
        return "manage/order/orderManage";
    }

    @GetMapping("/deliver")
    public String deliver(String orderId,Model model) {
        int orderId1 = Integer.parseInt(orderId);
        order = orderService.getOrder(orderId1);
        if(order.getStatus().equals("delivered") ){
            order.setStatus("not delivered");
            System.out.println("database has been changed to not delivered");
            //更新商家库存
            for (int i = 0; i < order.getLineItems().size(); i++) {
                String itemId = order.getLineItems().get(i).getItemId();
                System.out.println("item is "+itemId);
                int qtyLose = order.getLineItems().get(i).getQuantity();
                System.out.println("buying qty is "+qtyLose);
                int qtyNow = catalogService.getQTYFromInventory(itemId);
                System.out.println("now qty is "+qtyNow);
                catalogService.updateInventory(itemId,qtyNow+qtyLose);
            }
        }
        else{
            order.setStatus("delivered");
            System.out.println("database has been changed to delivered");
            //更新商家库存
            for (int i = 0; i < order.getLineItems().size(); i++) {
                String itemId = order.getLineItems().get(i).getItemId();
                System.out.println("item is "+itemId);
                int qtyLose = order.getLineItems().get(i).getQuantity();
                System.out.println("buying qty is "+qtyLose);
                int qtyNow = catalogService.getQTYFromInventory(itemId);
                System.out.println("now qty is "+qtyNow);
                catalogService.updateInventory(itemId,qtyNow-qtyLose);
            }
        }
        orderService.updateOrder(order);
        orderList = orderService.getOrdersList();
        session.setAttribute("allOrderList",orderList);
        return "manage/order/orderManage";
    }
    /***************************ACCOUNT*****************************************/
    @RequestMapping("/viewAccountInfor")
    public String viewAccountInfor(Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        Manager manager = (Manager) session.getAttribute("manager");
        List<Account> accountList = accountService.getallAccount();
        List<Account> accountList1 = accountService.getallAccountprofile();
        session.setAttribute("accountList",accountList);
        model.addAttribute("accountList",accountList);
        model.addAttribute("accountList1",accountList1);
        model.addAttribute("manager",manager);
        return "manage/account/UserinforManage";
    }
    @RequestMapping("/searchAccount")
    public String searchAccount(Model model,HttpServletRequest request){
        String keyword = request.getParameter("keyword");
        HttpSession session = request.getSession();
        Manager manager = (Manager) session.getAttribute("manager");
        List<Account> accountList = accountService.searchAccount(keyword);
        model.addAttribute("manager",manager);
        model.addAttribute("accountList",accountList);
        return "manage/account/UserinforManage";
    }
    @RequestMapping("/updateAccountPageOne")
    public String updateAccountPageOne(HttpServletRequest req,Model model){
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (Exception e) {
        }
        String username = req.getParameter("username");
        HttpSession session = req.getSession();
        Manager manager = (Manager) session.getAttribute("manager");
        Account account = accountService.getAccount(username);
        String password = req.getParameter("password");
        String firstName = req.getParameter("firstname");
        String lastName = req.getParameter("lastname");
        String email = req.getParameter("email");
        String city = req.getParameter("city");

        String country = req.getParameter("country");

        account.setUsername(username);
        account.setPassword(password);
        account.setFirstName(firstName);
        account.setLastName(lastName);
        account.setEmail(email);
        account.setCity(city);
        account.setCountry(country);
        accountService.updateAccount(account);
        model.addAttribute("manager",manager);

        List<Account> accountList = accountService.getallAccount();
        List<Account> accountList1 = accountService.getallAccountprofile();
        model.addAttribute("accountList",accountList);
        model.addAttribute("accountList1",accountList1);

        return "manage/account/UserinforManage";
    }
    @RequestMapping("/updateAccountPageTwo")
    public String updateAccountPageTwo(HttpServletRequest req,Model model){
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (Exception e) {
        }
        String username = req.getParameter("username");
        HttpSession session = req.getSession();
        Manager manager = (Manager) session.getAttribute("manager");
        Account account = accountService.getAccount(username);
        String address1 = req.getParameter("address1");
        String address2 = req.getParameter("address2");
        String status = req.getParameter("status");
        String state = req.getParameter("state");
        String zip = req.getParameter("zip");
        String phone = req.getParameter("phone");

        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setStatus(status);
        account.setState(state);
        account.setZip(zip);
        account.setPhone(phone);
        accountService.updateAccount(account);
        model.addAttribute("manager",manager);

        List<Account> accountList = accountService.getallAccount();
        List<Account> accountList1 = accountService.getallAccountprofile();
        model.addAttribute("accountList",accountList);
        model.addAttribute("accountList1",accountList1);
        return "";
    }
    @RequestMapping("/updateAccountprofile")
    public String updateAccountprofile(HttpServletRequest req,Model model){
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (Exception e) {
        }
        String username = req.getParameter("username");
        HttpSession session = req.getSession();
        Manager manager = (Manager) session.getAttribute("manager");
        Account account = accountService.getAccount(username);
        String languagePreference = req.getParameter("languagePreference");
        String favouriteCategoryId = req.getParameter("favouriteCategoryId");
        String listOption = req.getParameter("listOption");
        String bannerOption = req.getParameter("bannerOption");

        account.setLanguagePreference(languagePreference);
        account.setFavouriteCategoryId(favouriteCategoryId);
        account.setListOption(Boolean.parseBoolean(listOption));
        account.setBannerOption(Boolean.parseBoolean(bannerOption));
        accountService.updateAccount(account);

        model.addAttribute("manager",manager);

        List<Account> accountList = accountService.getallAccount();
        List<Account> accountList1 = accountService.getallAccountprofile();
        model.addAttribute("accountList",accountList);
        model.addAttribute("accountList1",accountList1);
        return "manage/account/UserinforManage";
    }
    @RequestMapping("/editAccount")
    public String editAccount(HttpServletRequest req,Model model){
        String username = req.getParameter("username");
        HttpSession session = req.getSession();
        Account account = accountService.getAccount(username);
        model.addAttribute("account",account);
        session.setAttribute("account",account);
        return "manage/account/EditAccount";
    }
    @RequestMapping("/deleteAccount")
    public String deleteAccount(HttpServletRequest req,Model model){
        String username = req.getParameter("username");
        accountService.deleteAccount(username);
        HttpSession session = req.getSession();
        Manager manager = (Manager) session.getAttribute("manager");
        model.addAttribute("manager",manager);
        List<Account> accountList = accountService.getallAccount();
        List<Account> accountList1 = accountService.getallAccountprofile();
        model.addAttribute("accountList",accountList);
        model.addAttribute("accountList1",accountList1);
        return "manage/account/UserinforManage";
    }

    @GetMapping("/updateInformation")
    public String UpdateInformationGet(String username,Model model)
    {
        account = accountService.getAccount(username);
        model.addAttribute("account",account);
        return "manage/account/accountUpdate";
    }

    @PostMapping("/updateInformation")
    public String UpdateInformationPost(HttpServletRequest req, HttpServletResponse response,Account account, Model model) {
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (Exception e) {

        }

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String firstName = req.getParameter("firstname");
        String lastName = req.getParameter("lastname");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address1 = req.getParameter("address1");
        String address2 = req.getParameter("address2");
        String city = req.getParameter("city");
        String state = req.getParameter("state");
        String zip = req.getParameter("zip");
        String country = req.getParameter("country");
        String languagePreference = req.getParameter("languagePreference");
        String favouriteCategoryId = req.getParameter("favouriteCategoryId");
//        String listOption = req.getParameter("listOption");
//        String bannerOption = req.getParameter("bannerOption");
        String a = req.getParameter("listOption");
        boolean listOption =false;
        if(a!=null&&a.equals("1"))
        {
            listOption= true;
        }
        String b = req.getParameter("bannerOption");
        boolean bannerOption = false;
        if(b!=null&&b.equals("1"))
        {
            bannerOption= true;
        }

        // 将密码进行MD5加密
        password= MD5Utils.md5(password);

                account.setUsername(username);
                account.setPassword(password);
                account.setFirstName(firstName);
                account.setLastName(lastName);
                account.setEmail(email);
                account.setPhone(phone);
                account.setAddress1(address1);
                account.setAddress2(address2);
                account.setCity(city);
                account.setState(state);
                account.setZip(zip);
                account.setCountry(country);
                account.setLanguagePreference(languagePreference);
                account.setFavouriteCategoryId(favouriteCategoryId);
                account.setListOption(listOption);
                account.setBannerOption(bannerOption);
                signInService.updateAccount(account);
                model.addAttribute("account", account);
                model.addAttribute("msg", "修改个人信息成功");

                return "manage/account/accountUpdate";

        }



    }
